package com.trade.module.database.operation;

import com.trade.common.utils.ResourceLoader;
import com.trade.module.database.basic.ConstConfig;
import lombok.extern.log4j.Log4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 控制数据库查询线程
 * Created by wangchun on 2016/4/12.
 */
@Log4j
public class SaveRecordThreadPool {

    private static SaveRecordThreadPool dbQueryThreadPool;
    private static BlockingQueue<Runnable> queue ;
    private static ThreadPoolExecutor executor;

    private SaveRecordThreadPool(){}

    public static SaveRecordThreadPool getInstance(){
        if (dbQueryThreadPool == null){
            dbQueryThreadPool = new SaveRecordThreadPool();
            // 保存任务的队列，无界队列
            queue = new LinkedBlockingQueue<Runnable>(); //固定为4的线程队列
            Integer queryThreadNum = getQueryThreadNum();
            log.info("保存数据并发线程数："+queryThreadNum);
            executor = new ThreadPoolExecutor(queryThreadNum, Integer.MAX_VALUE, 1, TimeUnit.DAYS, queue);
        }
        return dbQueryThreadPool;
    }

    /**
     * 从配置文件中获取查询线程数
     * @return
     */
    private static Integer getQueryThreadNum() {
        ResourceLoader resourceLoader = new ResourceLoader(ConstConfig.DDConfigFileName.DB_CONFIG);
        Integer queryThreadNum = 1;
        String queryThreadNumStr = resourceLoader.getPropertiesValue(ConstConfig.DDConfigPropertiesKey.SAVE_THREAD_NUM);
        if (queryThreadNumStr != null){
            queryThreadNum = Integer.valueOf(queryThreadNumStr);
        }
        return queryThreadNum;
    }

    public void execute(Runnable runnable) {
        executor.execute(runnable);
    }

    public void shutdown(){
        executor.shutdown();
    }

}
